<?php

class CommentController extends BaseController
{
	/**
	 * 
	 */
    public function listComment()
    {
        $comments = Comment::orderBy('id', 'desc')->paginate(20);
        $this->layout->title = 'Comment Listings';
        $this->layout->main = View::make('dash')->nest('content', 'comments.list', compact('comments'));
    }

    /**
     * 
     * @param Comment $comment
     */
    public function showComment(Comment $comment)
    {
        if (Request::ajax()) {
            return View::make('comments.show', compact('comment'));
        }
    }

    /**
     * 
     * @param Comment $comment
     */
    public function updateComment(Comment $comment)
    {
    	$comment->approved = Input::get('status');
    	$comment->save();
    	
    	$comment->post->comment_count = Comment::where('post_id', '=', $comment->post->id)->where('approved', '=', 1)
    																					  ->count();
    	$comment->post->save();
    	
    	return Redirect::back()->with('success', 'Comment ' . (($comment->approved === 'yes') ? 'Approved' : 'Disapproved'));
    }
    
    /**
     * 
     * @param Comment $comment
     */
    public function deleteComment(Comment $comment)
    {
        ($comment->approved === 'yes') ? $comment->post->decrement('comment_count') : '';
        $comment->delete();
        
        return Redirect::back()->with('success', 'Comment deleted!');
    }
    
	/**
	 * 
	 * @param Post $post
	 */
    public function newComment(Post $post)
    {
    	$comment = [
	    	'commenter' => Input::get('commenter'),
	    	'email' => Input::get('email'),
	    	'comment' => Input::get('comment'),
    	];
    	$rules = [
	    	'commenter' => 'required',
	    	'email' => 'required | email',
	    	'comment' => 'required',
    	];
    	
    	$valid = Validator::make($comment, $rules);
    	if ($valid->passes()) {
    		$comment = new Comment($comment);
    		$comment->approved = 'no';
    		$post->comments()->save($comment);
    		/* redirect back to the form portion of the page */
    		return Redirect::to(URL::previous() . '#reply')->with('success', 'Comment has been submitted and waiting for approval!');
    	} else {
    		return Redirect::to(URL::previous() . '#reply')->withErrors($valid)
    													   ->withInput();
    	}
    }

}